package com.helen.ui.userinfo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.db.UserHelper;
import com.helen.entity.LoginRegisterEntity;
import com.helen.entity.UpLoadPicEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.utils.ImageLoadUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.ActionSheetDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

/**
 * Created by yang on 2018/4/25.
 * 用户信息
 */

public class UserInfoActivity extends BaseActivity {
    public static final int USER_NAME = 0x11;
    public static final int USER_PHONE = 0x12;
    private static final int PHOTO_CARMERA = 0x13;
    private static final int PHOTO_PICK = 0x14;
    private static final int PHOTO_CUT = 0x15;
    private File tempFile = new File(Environment.getExternalStorageDirectory() + Constants.GLIDE_CARCH_DIR, getPhotoFileName());
    @BindView(R.id.circle_img)
    CircleImageView circleImg;
    @BindView(R.id.rl_img)
    RelativeLayout rlImg;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.ll_nick_name)
    LinearLayout llNickName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;
    @BindView(R.id.tv_bind_phone)
    TextView tvBindPhone;
    @BindView(R.id.ll_bind_phone)
    LinearLayout llBindPhone;
    @BindView(R.id.img_phone_arrows_right)
    ImageView imgPhoneArrowsRight;
    @BindView(R.id.tv_user_type)
    TextView tvUserType;
    @BindView(R.id.tv_register_time)
    TextView tvRegisterTime;
    private ActionSheetDialog.SheetItemColor sheetItemColor;
    private Intent ti;
    private RxPermissions rxPermissions;
    private List<UpLoadPicEntity > picList = new ArrayList<>();
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.user_info);
        rxPermissions = new RxPermissions(UserInfoActivity.this);
        initData(UserHelper.getInstance().getloginEntity(UserInfoActivity.this));
    }

    @Override
    protected void updateViews() {

    }

    private void initData(LoginRegisterEntity loginRegisterEntity) {
        if (loginRegisterEntity != null) {
            tvUserName.setText(loginRegisterEntity.getName());
            tvNickName.setText(loginRegisterEntity.getName());
            tvSex.setText(loginRegisterEntity.getSex() + "");
            if(TextUtils.isEmpty(loginRegisterEntity.getPhone())){
                imgPhoneArrowsRight.setVisibility(View.VISIBLE);
                tvBindPhone.setHint("未绑定");
            }else {
                tvBindPhone.setText(loginRegisterEntity.getPhone());
                imgPhoneArrowsRight.setVisibility(View.GONE);
            }

            tvUserType.setText(loginRegisterEntity.getType());
            tvRegisterTime.setText(loginRegisterEntity.getTime());
            ImageLoadUtil.displayImage(UserInfoActivity.this, circleImg,loginRegisterEntity.getImg(), R.mipmap.icon_person_head, R.mipmap.icon_person_head);

        }
    }


    @OnClick({R.id.rl_img, R.id.ll_nick_name, R.id.ll_sex, R.id.ll_bind_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_img:
                new ActionSheetDialog(UserInfoActivity.this)
                        .builder()
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if ((Build.VERSION.SDK_INT >= 23)) {
                                            onClickAllPermission();
                                        } else {
                                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                            // 指定调用相机拍照后照片的储存路径
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                                            startActivityForResult(intent, PHOTO_CARMERA);
                                        }


                                    }
                                })
                        .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        if ((Build.VERSION.SDK_INT >= 23)) {
                                            onClickWRITE();
                                        } else {
                                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                            startActivityForResult(intent, PHOTO_PICK);
                                        }

                                    }
                                }).show();


                break;
            case R.id.ll_nick_name:
                ti = new Intent(UserInfoActivity.this, UpdateUserNameActivity.class);
                ti.putExtra("userInfoName", tvNickName.getText().toString().trim());
                startActivityForResult(ti, USER_NAME);
                break;
            case R.id.ll_sex:
                sheetItemColor = ActionSheetDialog.SheetItemColor.ThemeColor;
                new ActionSheetDialog(UserInfoActivity.this)
                        .builder()
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("男", sheetItemColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        tvSex.setText("男");
                                        UpdateUserInfoData("", "1", "","");

                                    }
                                })
                        .addSheetItem("女", sheetItemColor,
                                new ActionSheetDialog.OnSheetItemClickListener() {
                                    @Override
                                    public void onClick(int which) {
                                        tvSex.setText("女");
                                        UpdateUserInfoData("", "0", "","");
                                    }
                                }).show();

                break;
            case R.id.ll_bind_phone:
                if(TextUtils.isEmpty(tvBindPhone.getText().toString().trim())){
                    ti = new Intent(UserInfoActivity.this, BindPhoneActivity.class);
                    startActivityForResult(ti, USER_PHONE);
                }

                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case USER_NAME:
                    if (data != null) {
                        String name = data.getStringExtra("userInfoName");
                        tvNickName.setText(name);
                        UpdateUserInfoData(name, "", "","");
                    }
                    break;
                case USER_PHONE:
                    break;
                case PHOTO_CARMERA:
                    try {
                        if (tempFile != null) {
                            startPhotoZoom(Uri.fromFile(tempFile), 150);
                        }
                    } catch (Exception e) {

                    }

                    break;
                case PHOTO_PICK:
                    try {
                        if (data != null) {
                            startPhotoZoom(data.getData(), 150);
                        }
                    } catch (Exception e) {

                    }

                    break;
                case PHOTO_CUT:
                    try {
                        if (null != data) {
                            setPicToView(data);
                            MyLog.e("yang", "tempFile.getPath()==" + tempFile.getPath());
                            UpdateUserPortraits(tempFile.getPath());
                        }
                    } catch (Exception e) {

                    }

                    break;
            }
        }
    }

    private void UpdateUserInfoData(final String name, final String sex, final String relativeurl,final String img) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(UserInfoActivity.this).getId() + "");
        if (!TextUtils.isEmpty(name)) {
            params.put("name", name);
        }
        if (!TextUtils.isEmpty(sex)) {
            params.put("sex", sex);
        }
        if (!TextUtils.isEmpty(relativeurl)) {
            params.put("img",relativeurl);
        }
        MyLog.e("yang", "img==" + img);
        EasyHttp.post(Constants.API_JSONAPI_UPDATEINFO)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "用户信息修改失败==" + e.toString());
                        MToast.makeTextShort(UserInfoActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.i("yang", "用户信息修改成功==" + result);
                        String data = PhoneUtils.checkResponseFlag(UserInfoActivity.this, result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(UserInfoActivity.this, "修改成功").show();
                            if (!TextUtils.isEmpty(name)) {
                                UserHelper.getInstance().getloginEntity(UserInfoActivity.this).setName(name);
                            }

                            if (!TextUtils.isEmpty(sex)) {
                                if (sex.equals("0")) {
                                    UserHelper.getInstance().getloginEntity(UserInfoActivity.this).setSex("女");
                                } else {
                                    UserHelper.getInstance().getloginEntity(UserInfoActivity.this).setSex("男");
                                }
                            }
                            if (!TextUtils.isEmpty(img)) {
                                UserHelper.getInstance().getloginEntity(UserInfoActivity.this).setImg(img);
                            }


                        }
                    }
                });
    }


    //上传用户头像
    private void UpdateUserPortraits(String imgUrl) {
        mMProgressDialog.show();
        String url = Constants.APP_API_BASE + Constants.API_JSONAPI_UPDATEIMG;
        RequestParams params = new RequestParams(url);
        params.setMultipart(true);
        try {
            params.addBodyParameter("file", new FileInputStream(new File(imgUrl)), "img/jpg", getPhotoFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "上传图片成功==" + result);
                String data = PhoneUtils.checkResponseFlag2(UserInfoActivity.this, result, TAG);
                if (data != null) {
                    picList = new Gson().fromJson(data, new TypeToken<List<UpLoadPicEntity>>() {
                    }.getType());
                    UpdateUserInfoData("", "", picList.get(0).getRelativeurl(),picList.get(0).getNeturl());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "上传图片失败=" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mMProgressDialog.dismiss();
            }
        });


    }


    public void onClickAllPermission() {
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@android.support.annotation.NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            // 指定调用相机拍照后照片的储存路径
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                            startActivityForResult(intent, PHOTO_CARMERA);
                        } else {
                            MToast.makeTextLong(UserInfoActivity.this, "权限拒绝").show();
                        }
                    }
                });

    }


    public void onClickWRITE() {
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@android.support.annotation.NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, PHOTO_PICK);
                        } else {
                            MToast.makeTextLong(UserInfoActivity.this, "读写权限拒绝").show();
                        }
                    }
                });

    }

    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CUT);
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToView(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (bundle != null) {
            Bitmap UserPortraitbitmap = bundle.getParcelable("data");
            circleImg.setImageBitmap(UserPortraitbitmap);
            saveCropPic(UserPortraitbitmap);

        }
    }

    //    图片上传命名
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    // 把裁剪后的图片保存到sdcard上
    private void saveCropPic(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fis = null;
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        try {
            fis = new FileOutputStream(tempFile);
            fis.write(baos.toByteArray());
            fis.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
